#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include <cstdlib>
#include <error.h>

class Sock
{
  public:
    static int Socket()
    {
      int listen_sockfd = socket(AF_INET, SOCK_STREAM, 0);
      if(listen_sockfd == -1)
      {
        fprintf(stderr, "socket: %s\n", strerror(errno));
        //perror();
        exit(2);
      }
      else
      {
        //fprintf(stdout, "Socket: %d\n", listen_sockfd);
        return listen_sockfd;  
      }
    }

    static void Bind(int listen_sockfd, uint16_t port)
    {
      struct sockaddr_in local;
      bzero(&local, sizeof(local));
      local.sin_family = AF_INET;
      local.sin_port = htons(port);
      local.sin_addr.s_addr = INADDR_ANY;
      socklen_t local_length = sizeof(sockaddr_in);
      if(bind(listen_sockfd, (struct sockaddr*)&local, local_length) == 0)
      {
        //fprintf(stdout, "Bind succed!\n");
        
      }
      else{
        fprintf(stderr, "Bind: %s\n", strerror(errno));
        exit(3);
      }
    }

    static void Listen(int listen_sockfd)
    {

      if(listen(listen_sockfd, 5) == 0)
      {
        //fprintf(stdout, "Listen succed!\n");
      }
      else
      {
        fprintf(stderr, "Listen: %s\n", strerror(errno));
        exit(4);
      }

    }

    static int Accept(int listen_sockfd)
    {
      struct sockaddr_in peer;
      socklen_t len = sizeof(struct sockaddr_in);
      int sockfd = accept(listen_sockfd, (struct sockaddr*)&peer, &len);
      if(sockfd == -1)
      {
        fprintf(stderr, "Accept: %s\n", strerror(errno));
        exit(5);
      }
      else
      {
        //fprintf(stdout, "Accept succed!\n");
        return sockfd;
      }
    }
};


